
package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.IDealWithMessage;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.provider.MediaStore;

import java.nio.channels.SocketChannel;

/**
 * 用来设置铃声的。
 * 
 * @author Administrator
 */
public class SettingManager implements IDealWithMessage {

    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {
        // TODO Auto-generated method stub
        return false;
    }

    public static Cursor query(Context context, Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder, int limit) {
        try {
            ContentResolver resolver = context.getContentResolver();
            if (resolver == null) {
                return null;
            }
            if (limit > 0) {
                uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
            }

            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
        } catch (UnsupportedOperationException ex) {
            return null;
        }

    }

    /**
     * 查询数据库，根据歌曲名称获取id。
     * @param context
     * @param name
     * @return
     */
    private static long getAudioIdByName(Context context, String name) {
        Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {
            MediaStore.Audio.Media._ID
        }, MediaStore.Audio.Media.DISPLAY_NAME + "=?", new String[] {
            name
        }, null, 0);
        long id = -1;
        if (c != null) {
            c.moveToFirst();
            if (!c.isAfterLast()) {
                id = c.getLong(0);
            }
        }
        return id;
    }

    /**
     * 设置铃声。
     * 
     * @param context
     * @param audio_id
     * @return
     */
    private static boolean setRingMusic(Context context, Long audio_id) {
        boolean success = false;
        try {
            Uri ringtoneUri = ContentUris.withAppendedId(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audio_id);
            // 短信铃声
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION,
                    ringtoneUri);
            // 设置告警
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM,
                    ringtoneUri);
            // 设置电话铃声
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE,
                    ringtoneUri);
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success;
    }

}
